//
//  WBBaseViewController.swift
//  WeiBoApp
//
//  Created by James on 2017/6/11.
//  Copyright © 2017年 James. All rights reserved.
//

import UIKit

//class WBBaseViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//Swift继承写法
//Swift中利用extension 可以把‘函数’按照功能分类，便于阅读和维护
// - extension 中不能有属性，不能重写父类本类的方法（extension里的可以）！重写父类方法是子类的事，扩展事对类的扩展
//基类控制器
class WBBaseViewController: UIViewController {
    
//    var userLogon = false
    
    ///访客试图 信息字典
    var visitorInfoDict : [String:String]?
    
    var tableView:UITableView?
    
    ///刷新控件
    var refreshControl:UIRefreshControl?
    
    //自定义导航条
    lazy var navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 64))
    //自定义导航项
    lazy var navItem = UINavigationItem()
    
    ///上拉刷新标记
    var isPush = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setUpUI()
        
        WBNetWorkManger.shared.userLogon ? loadData() : ()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess(n:)), name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
        
        print("---->viewDidLoad");
    }
    
    override var title: String?{
        didSet{//重写set方法
            navItem.title = title
        }
    }
    
    ///加载数据  具体的实现由子类写
    func loadData()  {
        //如果之类不实现任何方法，则关闭刷新
        print(WBNetWorkManger.shared)
        refreshControl?.endRefreshing()
    }
    
}


// MARK:设置界面
extension WBBaseViewController {
    fileprivate func setUpUI() {

        //取消自动缩进  如果隐藏了导航栏，会缩进20个点
        automaticallyAdjustsScrollViewInsets = false
        setUpNavBar()
//        userLogon ? setUpTableView() : setUpVisitorView()
        
        WBNetWorkManger.shared.userLogon ? setUpTableView() : setUpVisitorView()

    }
    
     func setUpTableView(){
        
        tableView = UITableView(frame: self.view.bounds, style: .plain)
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.contentInset = UIEdgeInsets(top: navBar.bounds.size.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        view.addSubview(tableView!)
        view.insertSubview(tableView!, belowSubview: navBar)
        
        //修改指示器的缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        
        //添加刷新控件
        refreshControl = UIRefreshControl()
        tableView?.addSubview(refreshControl!)
        //添加监听方法
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
    }
    
    fileprivate func setUpNavBar() {
        view.addSubview(navBar)
        navBar.items = [navItem]
        //1.设置navBar 整个背景的渲染颜色
        navBar.barTintColor = UIColor.white
        
        //2.设置title颜色
        navBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
        //3.设置系统按钮的文字渲染颜色
        navBar.tintColor = UIColor.orange
    }
    
    ///设置访客试图
    fileprivate func setUpVisitorView(){
        //1.添加view
        let visitorView = WBVisitorView(frame: view.bounds)
        visitorView.tag = 1
        view.insertSubview(visitorView, belowSubview: navBar)
        visitorView.visitorInfo = visitorInfoDict
        //2.设置点击事件
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        //3.设置导航条按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
    }
}

// MARK: - UITableViewDelegate,UITableViewDataSource
extension WBBaseViewController:UITableViewDelegate,UITableViewDataSource {
    //基类只是准备方法，子类需要具体的实现
    //子类的数据源方法 不需要super
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //只是没有语法错误
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //1.判断indexPath是不是最后一行,是的话就上拉刷新
        
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        if row < 0 || section < 0{
            return
        }
        
//        print("\(section) ---- \(row)")
        
        let count = tableView.numberOfRows(inSection: section)
        
        if row > (count-2) && indexPath.section == section && !isPush{
            isPush = true
            loadData()
//            print("上啦刷新")
        }
        
    }
}


extension WBBaseViewController{
    @objc fileprivate func login(){
        print("login")
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
    }
    
    @objc fileprivate func loginSuccess(n:Notification){
        print("登录成功\(n)")
        //更新UI  -->将访客试图替换为表格试图
//        view.removeFromSuperview()
        
        navItem.leftBarButtonItem = nil;
        navItem.rightBarButtonItem = nil
        
        //移除访客试图
        view.viewWithTag(1)?.removeFromSuperview()
        
        setUpTableView()

        loadData()
    }
    
    
    
    
    
    @objc fileprivate func register(){
        print("register")
    }
}
